import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import code from '@/code'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15e3
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.headers.Authorization = store.getters.token || ''
    if (config.method === 'post') {
      const data = config.data || {}
      config.data = qs.stringify({
        ...data
      })
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const data = response.data
    if (data.code !== 200 && data.status !== 1) {
      if (String(data.code).startsWith('30')) {
        if (data.code === 3003) {
          MessageBox(code[data.code], '友情提示', 'confirm').then(_ => {
            store.dispatch('user/logout').then(_ => {
              location.reload()
            })
          })
        } else {
          Message({
            message: code[data.code],
            type: 'error'
          })
        }
      }
    }
    if (response.status === 200 && data.code === 2010) {
      store.commit('app/HIDE_LOADING')
      Message({
        message: data.msg,
        type: 'error'
      })
    }
    return data
  },
  error => {
    if (error.message.includes('timeout')) {
      Message({
        message: '抱歉请求服务器超时',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.message.includes('Error')) {
      // Message({
      //   message: '服务器开了一会小差',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
    } else if (error.message.includes('502')) {
      location.reload()
    } else if (error.message.includes('500')) {
      Message({
        message: '服务器开了一会小差',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    store.commit('app/HIDE_LOADING')
    return Promise.reject(error)
  }
)

export default service
